package com.example.selectdorm.service;

import com.example.selectdorm.entity.DormitoryBuilding;
import com.example.selectdorm.entity.DormitoryRoom;
import com.example.selectdorm.entity.DormitoryUnit;
import com.example.selectdorm.repo.DormitoryBuildingRepository;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@AllArgsConstructor
public class DormitoryBuildingService {
    private final DormitoryBuildingRepository dormitoryBuildingRepository;
    private final DormitoryUnitService dormitoryUnitService;
    private final DormitoryRoomService dormitoryRoomService;

    public List<DormitoryBuilding> findAll() {
        return dormitoryBuildingRepository.findAll();
    }

    public Optional<DormitoryBuilding> findBuildingByName(String buildingName) {
        return dormitoryBuildingRepository.findDormitoryBuildingByBuildingName(buildingName);
    }


//  根据宿舍楼名称获取总床位数
//    TODO: 不够优雅
    public String getBedsByName(String buildingName){
        int bedsCount = 0;
        Optional<DormitoryBuilding> dormitoryBuilding = dormitoryBuildingRepository.findDormitoryBuildingByBuildingName(buildingName);

        if (!dormitoryBuilding.isPresent()){
            return "no such building";
        }

        Long buildingId = dormitoryBuilding.get().getId();

        List<DormitoryUnit> dormitoryUnits = dormitoryUnitService.findAllByBuildingId(buildingId);

        for(DormitoryUnit unit: dormitoryUnits) {
            Long unitId = unit.getId();
            List<DormitoryRoom> dormitoryRooms = dormitoryRoomService.findAllByUnitId(unitId);
            for (DormitoryRoom room : dormitoryRooms) {
                bedsCount += room.getRestBeds();
            }
        }

        return Integer.toString(bedsCount);
    }
    
//    获取符合订单条件的房间
    public List<DormitoryRoom> orderRoom(Long buildingId, String gender, int totalCount) {
        List<DormitoryUnit> units = dormitoryUnitService.findAllByBuildingId(buildingId);
        List<DormitoryRoom> allRooms = new ArrayList<>();
        for(DormitoryUnit unit: units) {
            List<DormitoryRoom> rooms = dormitoryRoomService.getRequiredRooms(unit.getId(), totalCount);
            if(!rooms.isEmpty())  {
                allRooms.addAll(rooms);
            }

        }
        return allRooms;
    }


}
